import { useQuery } from '@tanstack/solid-query'
import { Link, Outlet, createFileRoute } from '@tanstack/solid-router'
import { For, Suspense } from 'solid-js'
import { postsQueryOptions } from '~/utils/posts'

export const Route = createFileRoute('/posts')({
  loader: async ({ context }) => {
    await context.queryClient.ensureQueryData(postsQueryOptions())
  },
  head: () => ({ meta: [{ title: 'Posts' }] }),
  component: PostsComponent,
})

function PostsComponent() {
  const postsQuery = useQuery(() => postsQueryOptions())

  return (
    <div class="p-2 flex gap-2">
      <ul class="list-disc pl-4">
        <Suspense fallback={<div>Loading posts...</div>}>
          <For
            each={[
              ...(postsQuery.data || []),
              { id: 'i-do-not-exist', title: 'Non-existent Post' },
            ]}
          >
            {(post) => (
              <li class="whitespace-nowrap">
                <Link
                  to="/posts/$postId"
                  params={{
                    postId: post.id,
                  }}
                  class="block py-1 text-blue-800 hover:text-blue-600"
                  activeProps={{ class: 'text-black font-bold' }}
                >
                  <div>{post.title.substring(0, 20)}</div>
                </Link>
              </li>
            )}
          </For>
        </Suspense>
      </ul>
      <hr />
      <Outlet />
    </div>
  )
}
